package com.igeek.compus.backend.system.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.igeek.compus.backend.system.properties.WxConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {

    @Autowired
    private JedisUtil jedisUtil;

    public String getAccessToken() {
        // 先从redis中获取
        String token = jedisUtil.get("access_token");
        if(StrUtil.isEmpty(token)) {
            System.out.println("请求微信服务器获得token...");

            // redis中不存在，则去请求微信服务器获取
            WxConfig wxConfig = WxConfig.getInstance();

            //  构建微信请求参数
            String url = wxConfig.getProperty("wx.accessToken");
            Map<String, Object> map = new HashMap<>();
            map.put("grant_type", "client_credential");
            map.put("appid", wxConfig.getProperty("wx.appid"));
            map.put("secret", wxConfig.getProperty("wx.secret"));
            // 发送请求
            String result = HttpUtil.createGet(url).form(map).execute().body();

            JSONObject resultObj = JSONObject.parseObject(result);
            if(resultObj != null) {
                Object obj = resultObj.get("access_token");
                if(obj != null) {
                    token = (String) obj;

                    // 存至redis
                    jedisUtil.setex("access_token", 7000, token);
                }
            }
        }
        return token;
    }
}
